package com.hangzhou.xyj.db;

import android.content.Context;

import com.hangzhou.xyj.model.DramaModel;
import com.hangzhou.xyj.model.RecordModel;
import com.hangzhou.xyj.utils.StringUtil;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.List;

/**
 * @author : neo.duan
 * @date : 	  2016年2月23日
 * @desc : 关于戏曲的本地数据库操作
 */

public class RecordDao {
    private Dao<RecordModel, String> mDao;
    private DataHelper mHelper = null;

    public RecordDao(Context context) {
        this.mHelper = OpenHelperManager.getHelper(context, DataHelper.class);
        try {
            this.mDao = mHelper.getDao(RecordModel.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * 添加或更新本地戏曲
     *
     * @param info
     */
    public void addDrama(RecordModel info) {
        if (info == null) return;
        try {
            mDao.createOrUpdate(info);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据用户id获取戏曲信息
     *
     * @param dramaId
     * @return
     */
    public RecordModel getDrama(String dramaId) {
        if (StringUtil.isBlank(dramaId)) return null;
        RecordModel info = null;
        try {
            List<RecordModel> dramaModels = mDao.queryBuilder().where().eq(DramaModel.DRAMA_ID, dramaId).query();
            if (dramaModels == null || dramaModels.isEmpty()) {
                info = new RecordModel();
            } else {
                info = dramaModels.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return info;
    }

    /**
     * 获取所有本地戏曲（倒序）
     *
     * @return
     */
    public List<RecordModel> getDramasByUser(String userId) {
        if (StringUtil.isBlank(userId)) return null;
        try {
            return mDao.queryBuilder().orderBy("_createTime", false)
                    .where().eq(RecordModel.USER_ID, userId).query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除录制信息
     *
     * @param model
     * @throws SQLException
     */
    public void delete(RecordModel model) throws SQLException {
        if (model == null) {
            return;
        }
        mDao.delete(model);
    }
}
